package com.system.locale;

import java.util.Locale;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.theme.CookieThemeResolver;
/**
 * 国际化资源配置
 */
@Configuration
@ConfigurationProperties(value = "spring.messages", ignoreNestedProperties = false)
public class MessageResourceConfig {

	private String basename;
	private int cacheSeconds;
	private String encoding;
	
	public String getBasename() {
		return basename;
	}

	public void setBasename(String basename) {
		this.basename = basename;
	}

	public int getCacheSeconds() {
		return cacheSeconds;
	}

	public void setCacheSeconds(int cacheSeconds) {
		this.cacheSeconds = cacheSeconds;
	}

	public String getEncoding() {
		return encoding;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

    /**
     * 国际化解析器
     * @return
     */
    @Bean
    public LocaleResolver localeResolver(){
    	//CookieLocaleResolver slr = new CookieLocaleResolver();
    	SessionLocaleResolver slr = new SessionLocaleResolver();
    	slr.setDefaultLocale(Locale.CHINA);
    	return slr;
    }
    
    /**
     * 主题解析器
     * @return
     */
    @Bean
    public ThemeResolver themeResolver(){
    	CookieThemeResolver slr = new CookieThemeResolver();
    	slr.setCookieName("theme");
    	slr.setCookiePath("/");
    	slr.setCookieMaxAge(31536000);
    	slr.setDefaultThemeName("default");
    	return slr;
    }
    
    /**
     * 重新加载配置
     * @return
     */
    @Bean
    public ReloadableResourceBundleMessageSource messageSource(){
    	ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    	if(this.getBasename().indexOf(",") == -1){
    		messageSource.setBasename(this.getBasename());
    	}else{
    		messageSource.setBasenames(this.getBasename().split(","));
    	}
    	messageSource.setCacheSeconds(this.getCacheSeconds());
    	messageSource.setUseCodeAsDefaultMessage(true);
    	messageSource.setDefaultEncoding(this.getEncoding());
    	return messageSource;
    }
}
